<template>
  <n-card :bordered="false" class="mt-4 proCard">
    <BasicForm @register="register" @submit="handleSubmit">
      <template #timeSelect="{ model, field }">
        <n-date-picker
          v-model:formatted-value="model[field]"
          clearable
          type="daterange"
          value-format="yyyy-MM-dd"
        />
      </template>
      <template #ltvDays="{ model, field }">
        <n-input v-model:value="model[field]" clearable placeholder="格式示例：LCS5" />
      </template>
    </BasicForm>
  </n-card>
  <BasicTable
    ref="actionRef"
    :columns="tableCols"
    :request="loadDataTable"
    :row-key="(row) => row.id"
    :scroll-x="2048"
  >
    <template #toolbar>
      <n-button type="primary" @click="reloadTable">刷新数据</n-button>
    </template>
  </BasicTable>
</template>

<script lang="ts" setup>
  import { onMounted, ref, unref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { BasicTable } from '@/components/Table';
  import { getStatisticsArppuList } from '@/api/statistics/daily';

  const message = useMessage();

  interface httpReqParms {
    timeFilter: string;
    aRDailyFilter: string;
  }

  interface tableCol {
    key: string;
    title: string;
    width: number;
  }

  interface DataRow {
    [key: string]: string;
  }

  let tableCols = ref<tableCol[]>([]);
  const actionRef = ref();

  let reqParms = ref(<httpReqParms>{
    timeFilter: '',
    aRDailyFilter: '',
  });

  const schemas: FormSchema[] = [
    {
      field: 'ltvDays',
      component: 'NInput',
      label: '留存天数：',
      slot: 'ltvDays',
    },
    {
      field: 'timeSelect',
      label: '留存日期：',
      componentProps: {
        placeholder: '日期',
      },
      slot: 'timeSelect',
    },
  ];

  const [register] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas: schemas,
  });

  const handleSubmit = (values: Recordable) => {
    if (values.ltvDays && !/^LCS\d+/.test(values.ltvDays)) {
      message.warning('留存天数格式错误！');
      return;
    }
    reqParms.value.timeFilter = values.timeSelect
      ? values.timeSelect[0] + ':' + values.timeSelect[1]
      : '';
    reqParms.value.aRDailyFilter = values.ltvDays ? values.ltvDays : '';
    genTableColKeyHandle();
    reloadTable();
  };

  //table 列
  const genTableColKeyHandle = () => {
    tableCols.value = [];
    tableCols.value.push(<tableCol>{
      key: 'date',
      title: '注册日期',
      width: 97,
    });
    let colRange =
      reqParms.value.aRDailyFilter === '' ? 25 : Number(reqParms.value.aRDailyFilter.substring(3));
    for (let i = 1; i <= colRange; ) {
      let lcsKey = i <= 90 ? i : (i / 30 + 1) * 30;
      let title = i === 1 ? '首日用户' : i === 2 ? '次留' : lcsKey + '留';
      let width = i === 1 ? 90 : 75;
      tableCols.value.push(<tableCol>{
        key: 'LCS' + lcsKey,
        title: title,
        width: width,
      });

      if (i <= 90) {
        i++;
      } else {
        i += 30;
      }
    }
  };

  onMounted(() => {
    genTableColKeyHandle();
  });

  const loadDataTable = async () => {
    let data = await getStatisticsArppuList(unref(reqParms));
    let rows: DataRow[] = [];
    for (const [date, values] of Object.entries(data)) {
      if (typeof values === 'object' && values !== null) {
        let row: DataRow = {};
        row['date'] = date as string;
        for (const key in values) {
          if (key === 'firstDayTotalCount') {
            row['LCS1'] = String(values[key]);
          } else {
            row[key] = values[key] as string;
          }
        }
        rows.push(row);
      }
    }
    rows.sort((a, b) => {
      return new Date(b.date).getTime() - new Date(a.date).getTime();
    });
    return { list: rows, total: rows.length, pageSize: 10, page: 1 };
  };

  const reloadTable = () => {
    actionRef.value.reload();
  };
</script>

<style lang="less" scoped></style>
